package xyz.xuminghai;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.noear.snack.ONode;
import org.noear.snack.core.Options;
import xyz.xuminghai.User.Sex;

/**
 *
 * @author xuMingHai
 */
public class Main {
	public static void main(String[] args) throws ClassNotFoundException {

		User user = new User("user-1", "张三", (byte) 0X12, Sex.MALE);
		System.out.println("user = " + user);
		String userString = ONode.serialize(user);
		System.out.println("userString = " + userString);
		User user1 = ONode.deserialize(userString);
		System.out.println("user1 = " + user1);

		MyClassLoader myClassLoader = new MyClassLoader();
		Class<?> myUserClass = myClassLoader.loadClass(User.class.getName());
		System.out.println("user.getClass().equals(myUserClass) = " + user.getClass().equals(myUserClass));

		try {
			Object myObject = myUserClass.newInstance();
			Method setIdMethod = myUserClass.getMethod("setId", String.class);
			setIdMethod.invoke(myObject, "2");
			Method setNameMethod = myUserClass.getMethod("setName", String.class);
			setNameMethod.invoke(myObject, "李四");
			Method setAgeMethod = myUserClass.getMethod("setAge", byte.class);
			setAgeMethod.invoke(myObject, (byte) 23);
//			Method setSexMethod = myUserClass.getMethod("setSex", Sex.class);
//			setSexMethod.invoke(myObject, Sex.MALE);


			Options options = Options.serialize();
			//指定类加载器
			options.setClassLoader(myObject.getClass().getClassLoader());

			String myUserString = ONode.load(myObject, options).toJson();
/*			User myUser = ONode.deserialize(myUserString, myUserClass);
			myUser.setSex(Sex.FEMALE);
			System.out.println("myUser = " + myUser);
			System.out.println(myUser.getSex() == Sex.FEMALE);
			System.out.println("user.getClass().equals(myUser.getClass()) = " + user.getClass().equals(myUser.getClass()));*/

			Object o = ONode.load(myUserString, options).toObject();
			System.out.println("user.getClass().equals(o.getClass()) = " + user.getClass().equals(o.getClass()));

			System.out.println("user.getClass().equals(myUserClass) = " + user.getClass().equals(myUserClass));
			System.out.println("myUserClass.equals(o.getClass()) = " + myUserClass.equals(o.getClass()));
			System.out.println("myUserClass.isAssignableFrom(o.getClass()) = " + myUserClass.isAssignableFrom(o.getClass()));
		}
		catch (InstantiationException | IllegalAccessException |NoSuchMethodException |
			   InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}


}